<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlxstut - Tutorial for writing XSUBs - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlxstut">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlxstut.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlxstut">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlxstut">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlxstut">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlxstut">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlxstut">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlxstut">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlxstut">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlxstut">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlxstut">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlxstut">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlxstut">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlxstut">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlxstut">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlxstut">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlxstut">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlxstut">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlxstut">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlxstut">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlxstut">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlxstut">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlxstut">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlxstut">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlxstut">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlxstut">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlxstut">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlxstut">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlxstut">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlxstut">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlxstut">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlxstut">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlxstut">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlxstut">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlxstut">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlxstut">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlxstut">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlxstut">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlxstut">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlxstut">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlxstut">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlxstut">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlxstut">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlxstut">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlxstut">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlxstut">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlxstut">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlxstut">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlxstut">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlxstut">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlxstut">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlxstut">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlxstut">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlxstut">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlxstut">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlxstut">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlxstut">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlxstut">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlxstut">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlxstut">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlxstut">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlxstut">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlxstut">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlxstut">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlxstut">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlxstut">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlxstut">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlxstut">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlxstut">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlxstut">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlxstut">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlxstut">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlxstut">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlxstut">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlxstut">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlxstut">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlxstut">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlxstut">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlxstut">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlxstut">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlxstut">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlxstut">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlxstut.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlxstut">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlxstut">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlxstut">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlxstut">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlxstut">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlxstut">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlxstut">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlxstut">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlxstut">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlxstut">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlxstut">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlxstut">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlxstut">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlxstut">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlxstut">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlxstut">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlxstut">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlxstut">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlxstut">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlxstut">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlxstut">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlxstut">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlxstut">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlxstut">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlxstut">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlxstut">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlxstut">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlxstut">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlxstut">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlxstut">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlxstut">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlxstut">5.35.1</a>
          <a class="dropdown-item active" href="perlxstut.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlxstut.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlxstut.html">perlxstut</a>
          <div id="more">
            (<a href="perlxstut.txt">source</a>,
            <a href="https://metacpan.org/pod/perlxstut">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#SPECIAL-NOTES">SPECIAL NOTES</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#make">make</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Version-caveat">Version caveat</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Dynamic-Loading-versus-Static-Loading">Dynamic Loading versus Static Loading</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Threads-and-PERL_NO_GET_CONTEXT">Threads and PERL_NO_GET_CONTEXT</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#TUTORIAL">TUTORIAL</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-1">EXAMPLE 1</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-2">EXAMPLE 2</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#What-has-gone-on?">What has gone on?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Writing-good-test-scripts">Writing good test scripts</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-3">EXAMPLE 3</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#What&#39;s-new-here?">What&#39;s new here?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Input-and-Output-Parameters">Input and Output Parameters</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#The-XSUBPP-Program">The XSUBPP Program</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#The-TYPEMAP-file">The TYPEMAP file</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Warning-about-Output-Arguments">Warning about Output Arguments</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-4">EXAMPLE 4</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#What-has-happened-here?">What has happened here?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Anatomy-of-.xs-file">Anatomy of .xs file</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Getting-the-fat-out-of-XSUBs">Getting the fat out of XSUBs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#More-about-XSUB-arguments">More about XSUB arguments</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#The-Argument-Stack">The Argument Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Extending-your-Extension">Extending your Extension</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Documenting-your-Extension">Documenting your Extension</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Installing-your-Extension">Installing your Extension</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-5">EXAMPLE 5</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#New-Things-in-this-Example">New Things in this Example</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-6">EXAMPLE 6</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#New-Things-in-this-Example1">New Things in this Example</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-7-(Coming-Soon)">EXAMPLE 7 (Coming Soon)</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-8-(Coming-Soon)">EXAMPLE 8 (Coming Soon)</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#EXAMPLE-9-Passing-open-files-to-XSes">EXAMPLE 9 Passing open files to XSes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Troubleshooting-these-Examples">Troubleshooting these Examples</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#See-also">See also</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Author">Author</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlxstut.html#Last-Changed">Last Changed</a>
              </li>
          </ul>

              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlxstut.html#NAME">#</a>NAME</h1>

<p>perlxstut - Tutorial for writing XSUBs</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlxstut.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This tutorial will educate the reader on the steps involved in creating a Perl extension. The reader is assumed to have access to <a href="perlguts.html">perlguts</a>, <a href="perlapi.html">perlapi</a> and <a href="perlxs.html">perlxs</a>.</p>

<p>This tutorial starts with very simple examples and becomes more complex, with each new example adding new features. Certain concepts may not be completely explained until later in the tutorial in order to slowly ease the reader into building extensions.</p>

<p>This tutorial was written from a Unix point of view. Where I know them to be otherwise different for other platforms (e.g. Win32), I will list them. If you find something that was missed, please let me know.</p>

<h1 id="SPECIAL-NOTES"><a class="permalink" href="perlxstut.html#SPECIAL-NOTES">#</a><a id="SPECIAL"></a>SPECIAL NOTES</h1>

<h2 id="make"><a class="permalink" href="perlxstut.html#make">#</a>make</h2>

<p>This tutorial assumes that the make program that Perl is configured to use is called <code>make</code>. Instead of running &quot;make&quot; in the examples that follow, you may have to substitute whatever make program Perl has been configured to use. Running <b>perl -V:make</b> should tell you what it is.</p>

<h2 id="Version-caveat"><a class="permalink" href="perlxstut.html#Version-caveat">#</a><a id="Version"></a>Version caveat</h2>

<p>When writing a Perl extension for general consumption, one should expect that the extension will be used with versions of Perl different from the version available on your machine. Since you are reading this document, the version of Perl on your machine is probably 5.005 or later, but the users of your extension may have more ancient versions.</p>

<p>To understand what kinds of incompatibilities one may expect, and in the rare case that the version of Perl on your machine is older than this document, see the section on &quot;Troubleshooting these Examples&quot; for more information.</p>

<p>If your extension uses some features of Perl which are not available on older releases of Perl, your users would appreciate an early meaningful warning. You would probably put this information into the <i>README</i> file, but nowadays installation of extensions may be performed automatically, guided by <i>CPAN.pm</i> module or other tools.</p>

<p>In MakeMaker-based installations, <i>Makefile.PL</i> provides the earliest opportunity to perform version checks. One can put something like this in <i>Makefile.PL</i> for this purpose:</p>

<pre><code>eval { require 5.007 }
    or die &lt;&lt;EOD;
############
### This module uses frobnication framework which is not available
### before version 5.007 of Perl.  Upgrade your Perl before
### installing Kara::Mba.
############
EOD</code></pre>

<h2 id="Dynamic-Loading-versus-Static-Loading"><a class="permalink" href="perlxstut.html#Dynamic-Loading-versus-Static-Loading">#</a><a id="Dynamic"></a>Dynamic Loading versus Static Loading</h2>

<p>It is commonly thought that if a system does not have the capability to dynamically load a library, you cannot build XSUBs. This is incorrect. You <i>can</i> build them, but you must link the XSUBs subroutines with the rest of Perl, creating a new executable. This situation is similar to Perl 4.</p>

<p>This tutorial can still be used on such a system. The XSUB build mechanism will check the system and build a dynamically-loadable library if possible, or else a static library and then, optionally, a new statically-linked executable with that static library linked in.</p>

<p>Should you wish to build a statically-linked executable on a system which can dynamically load libraries, you may, in all the following examples, where the command &quot;<code>make</code>&quot; with no arguments is executed, run the command &quot;<code>make perl</code>&quot; instead.</p>

<p>If you have generated such a statically-linked executable by choice, then instead of saying &quot;<code>make test</code>&quot;, you should say &quot;<code>make test_static</code>&quot;. On systems that cannot build dynamically-loadable libraries at all, simply saying &quot;<code>make test</code>&quot; is sufficient.</p>

<h2 id="Threads-and-PERL_NO_GET_CONTEXT"><a class="permalink" href="perlxstut.html#Threads-and-PERL_NO_GET_CONTEXT">#</a><a id="Threads"></a>Threads and PERL_NO_GET_CONTEXT</h2>

<p>For threaded builds, perl requires the context pointer for the current thread, without <code>PERL_NO_GET_CONTEXT</code>, perl will call a function to retrieve the context.</p>

<p>For improved performance, include:</p>

<pre><code class="plaintext">#define PERL_NO_GET_CONTEXT</code></pre>

<p>as shown below.</p>

<p>For more details, see <a href="perlguts.html#How-multiple-interpreters-and-concurrency-are-supported">perlguts</a>.</p>

<h1 id="TUTORIAL"><a class="permalink" href="perlxstut.html#TUTORIAL">#</a>TUTORIAL</h1>

<p>Now let&#39;s go on with the show!</p>

<h2 id="EXAMPLE-1"><a class="permalink" href="perlxstut.html#EXAMPLE-1">#</a><a id="EXAMPLE"></a>EXAMPLE 1</h2>

<p>Our first extension will be very simple. When we call the routine in the extension, it will print out a well-known message and return.</p>

<p>Run &quot;<code>h2xs -A -n Mytest</code>&quot;. This creates a directory named Mytest, possibly under ext/ if that directory exists in the current working directory. Several files will be created under the Mytest dir, including MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes.</p>

<p>The MANIFEST file contains the names of all the files just created in the Mytest directory.</p>

<p>The file Makefile.PL should look something like this:</p>

<pre><code>use ExtUtils::MakeMaker;

# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.
WriteMakefile(
    NAME         =&gt; &#39;Mytest&#39;,
    VERSION_FROM =&gt; &#39;Mytest.pm&#39;, # finds $VERSION
    LIBS         =&gt; [&#39;&#39;],        # e.g., &#39;-lm&#39;
    DEFINE       =&gt; &#39;&#39;,          # e.g., &#39;-DHAVE_SOMETHING&#39;
    INC          =&gt; &#39;-I&#39;,        # e.g., &#39;-I. -I/usr/include/other&#39;
);</code></pre>

<p>The file Mytest.pm should start with something like this:</p>

<pre><code>package Mytest;

use 5.008008;
use strict;
use warnings;

require Exporter;

our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( &#39;all&#39; =&gt; [ qw(

) ] );

our @EXPORT_OK = ( @{ $EXPORT_TAGS{&#39;all&#39;} } );

our @EXPORT = qw(

);

our $VERSION = &#39;0.01&#39;;

require XSLoader;
XSLoader::load(&#39;Mytest&#39;, $VERSION);

# Preloaded methods go here.

1;
__END__
# Below is the stub of documentation for your module. You better
# edit it!</code></pre>

<p>The rest of the .pm file contains sample code for providing documentation for the extension.</p>

<p>Finally, the Mytest.xs file should look something like this:</p>

<pre><code class="plaintext">#define PERL_NO_GET_CONTEXT
#include &quot;EXTERN.h&quot;
#include &quot;perl.h&quot;
#include &quot;XSUB.h&quot;

#include &quot;ppport.h&quot;

MODULE = Mytest		PACKAGE = Mytest</code></pre>

<p>Let&#39;s edit the .xs file by adding this to the end of the file:</p>

<pre><code>    void
    hello()
	CODE:
	    printf(&quot;Hello, world!\n&quot;);</code></pre>

<p>It is okay for the lines starting at the &quot;CODE:&quot; line to not be indented. However, for readability purposes, it is suggested that you indent CODE: one level and the lines following one more level.</p>

<p>Now we&#39;ll run &quot;<code>perl Makefile.PL</code>&quot;. This will create a real Makefile, which make needs. Its output looks something like:</p>

<pre><code class="plaintext">% perl Makefile.PL
Checking if your kit is complete...
Looks good
Writing Makefile for Mytest
%</code></pre>

<p>Now, running make will produce output that looks something like this (some long lines have been shortened for clarity and some extraneous lines have been deleted):</p>

<pre><code class="plaintext">% make
cp lib/Mytest.pm blib/lib/Mytest.pm
perl xsubpp  -typemap typemap  Mytest.xs &gt; Mytest.xsc &amp;&amp; \
mv Mytest.xsc Mytest.c
Please specify prototyping behavior for Mytest.xs (see perlxs manual)
cc -c     Mytest.c
Running Mkbootstrap for Mytest ()
chmod 644 Mytest.bs
rm -f blib/arch/auto/Mytest/Mytest.so
cc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so

chmod 755 blib/arch/auto/Mytest/Mytest.so
cp Mytest.bs blib/arch/auto/Mytest/Mytest.bs
chmod 644 blib/arch/auto/Mytest/Mytest.bs
Manifying blib/man3/Mytest.3pm
%</code></pre>

<p>You can safely ignore the line about &quot;prototyping behavior&quot; - it is explained in <a href="perlxs.html#The-PROTOTYPES%3A-Keyword">&quot;The PROTOTYPES: Keyword&quot; in perlxs</a>.</p>

<p>Perl has its own special way of easily writing test scripts, but for this example only, we&#39;ll create our own test script. Create a file called hello that looks like this:</p>

<pre><code>#! /opt/perl5/bin/perl

use ExtUtils::testlib;

use Mytest;

Mytest::hello();</code></pre>

<p>Now we make the script executable (<code>chmod +x hello</code>), run the script and we should see the following output:</p>

<pre><code class="plaintext">% ./hello
Hello, world!
%</code></pre>

<h2 id="EXAMPLE-2"><a class="permalink" href="perlxstut.html#EXAMPLE-2">#</a><a id="EXAMPLE1"></a>EXAMPLE 2</h2>

<p>Now let&#39;s add to our extension a subroutine that will take a single numeric argument as input and return 1 if the number is even or 0 if the number is odd.</p>

<p>Add the following to the end of Mytest.xs:</p>

<pre><code>    int
    is_even(input)
	    int input
	CODE:
	    RETVAL = (input % 2 == 0);
	OUTPUT:
	    RETVAL</code></pre>

<p>There does not need to be whitespace at the start of the &quot;<code>int input</code>&quot; line, but it is useful for improving readability. Placing a semi-colon at the end of that line is also optional. Any amount and kind of whitespace may be placed between the &quot;<code>int</code>&quot; and &quot;<code>input</code>&quot;.</p>

<p>Now re-run make to rebuild our new shared library.</p>

<p>Now perform the same steps as before, generating a Makefile from the Makefile.PL file, and running make.</p>

<p>In order to test that our extension works, we now need to look at the file Mytest.t. This file is set up to imitate the same kind of testing structure that Perl itself has. Within the test script, you perform a number of tests to confirm the behavior of the extension, printing &quot;ok&quot; when the test is correct, &quot;not ok&quot; when it is not.</p>

<pre><code>use Test::More tests =&gt; 4;
BEGIN { use_ok(&#39;Mytest&#39;) };

#########################

# Insert your test code below, the Test::More module is use()ed here
# so read its man page ( perldoc Test::More ) for help writing this
# test script.

is( Mytest::is_even(0), 1 );
is( Mytest::is_even(1), 0 );
is( Mytest::is_even(2), 1 );</code></pre>

<p>We will be calling the test script through the command &quot;<code>make test</code>&quot;. You should see output that looks something like this:</p>

<pre><code>%make test
PERL_DL_NONLAZY=1 /usr/bin/perl &quot;-MExtUtils::Command::MM&quot; &quot;-e&quot;
&quot;test_harness(0, &#39;blib/lib&#39;, &#39;blib/arch&#39;)&quot; t/*.t
t/Mytest....ok
All tests successful.
Files=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU)
%</code></pre>

<h2 id="What-has-gone-on?"><a class="permalink" href="perlxstut.html#What-has-gone-on?">#</a><a id="What"></a><a id="What-has-gone-on"></a>What has gone on?</h2>

<p>The program h2xs is the starting point for creating extensions. In later examples we&#39;ll see how we can use h2xs to read header files and generate templates to connect to C routines.</p>

<p>h2xs creates a number of files in the extension directory. The file Makefile.PL is a perl script which will generate a true Makefile to build the extension. We&#39;ll take a closer look at it later.</p>

<p>The .pm and .xs files contain the meat of the extension. The .xs file holds the C routines that make up the extension. The .pm file contains routines that tell Perl how to load your extension.</p>

<p>Generating the Makefile and running <code>make</code> created a directory called blib (which stands for &quot;build library&quot;) in the current working directory. This directory will contain the shared library that we will build. Once we have tested it, we can install it into its final location.</p>

<p>Invoking the test script via &quot;<code>make test</code>&quot; did something very important. It invoked perl with all those <code>-I</code> arguments so that it could find the various files that are part of the extension. It is <i>very</i> important that while you are still testing extensions that you use &quot;<code>make test</code>&quot;. If you try to run the test script all by itself, you will get a fatal error. Another reason it is important to use &quot;<code>make test</code>&quot; to run your test script is that if you are testing an upgrade to an already-existing version, using &quot;<code>make test</code>&quot; ensures that you will test your new extension, not the already-existing version.</p>

<p>When Perl sees a <code>use extension;</code>, it searches for a file with the same name as the <code>use</code>&#39;d extension that has a .pm suffix. If that file cannot be found, Perl dies with a fatal error. The default search path is contained in the <code>@INC</code> array.</p>

<p>In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic Loader extensions. It then sets the <code>@ISA</code> and <code>@EXPORT</code> arrays and the <code>$VERSION</code> scalar; finally it tells perl to bootstrap the module. Perl will call its dynamic loader routine (if there is one) and load the shared library.</p>

<p>The two arrays <code>@ISA</code> and <code>@EXPORT</code> are very important. The <code>@ISA</code> array contains a list of other packages in which to search for methods (or subroutines) that do not exist in the current package. This is usually only important for object-oriented extensions (which we will talk about much later), and so usually doesn&#39;t need to be modified.</p>

<p>The <code>@EXPORT</code> array tells Perl which of the extension&#39;s variables and subroutines should be placed into the calling package&#39;s namespace. Because you don&#39;t know if the user has already used your variable and subroutine names, it&#39;s vitally important to carefully select what to export. Do <i>not</i> export method or variable names <i>by default</i> without a good reason.</p>

<p>As a general rule, if the module is trying to be object-oriented then don&#39;t export anything. If it&#39;s just a collection of functions and variables, then you can export them via another array, called <code>@EXPORT_OK</code>. This array does not automatically place its subroutine and variable names into the namespace unless the user specifically requests that this be done.</p>

<p>See <a href="perlmod.html">perlmod</a> for more information.</p>

<p>The <code>$VERSION</code> variable is used to ensure that the .pm file and the shared library are &quot;in sync&quot; with each other. Any time you make changes to the .pm or .xs files, you should increment the value of this variable.</p>

<h2 id="Writing-good-test-scripts"><a class="permalink" href="perlxstut.html#Writing-good-test-scripts">#</a><a id="Writing"></a>Writing good test scripts</h2>

<p>The importance of writing good test scripts cannot be over-emphasized. You should closely follow the &quot;ok/not ok&quot; style that Perl itself uses, so that it is very easy and unambiguous to determine the outcome of each test case. When you find and fix a bug, make sure you add a test case for it.</p>

<p>By running &quot;<code>make test</code>&quot;, you ensure that your Mytest.t script runs and uses the correct version of your extension. If you have many test cases, save your test files in the &quot;t&quot; directory and use the suffix &quot;.t&quot;. When you run &quot;<code>make test</code>&quot;, all of these test files will be executed.</p>

<h2 id="EXAMPLE-3"><a class="permalink" href="perlxstut.html#EXAMPLE-3">#</a><a id="EXAMPLE2"></a>EXAMPLE 3</h2>

<p>Our third extension will take one argument as its input, round off that value, and set the <i>argument</i> to the rounded value.</p>

<p>Add the following to the end of Mytest.xs:</p>

<pre><code>void
round(arg)
	double  arg
    CODE:
	if (arg &gt; 0.0) {
		arg = floor(arg + 0.5);
	} else if (arg &lt; 0.0) {
		arg = ceil(arg - 0.5);
	} else {
		arg = 0.0;
	}
    OUTPUT:
	arg</code></pre>

<p>Edit the Makefile.PL file so that the corresponding line looks like this:</p>

<pre><code class="plaintext">LIBS      =&gt; [&#39;-lm&#39;],   # e.g., &#39;-lm&#39;</code></pre>

<p>Generate the Makefile and run make. Change the test number in Mytest.t to &quot;9&quot; and add the following tests:</p>

<pre><code>my $i;

$i = -1.5;
Mytest::round($i);
is( $i, -2.0, &#39;Rounding -1.5 to -2.0&#39; );

$i = -1.1;
Mytest::round($i);
is( $i, -1.0, &#39;Rounding -1.1 to -1.0&#39; );

$i = 0.0;
Mytest::round($i);
is( $i, 0.0, &#39;Rounding 0.0 to 0.0&#39; );

$i = 0.5;
Mytest::round($i);
is( $i, 1.0, &#39;Rounding 0.5 to 1.0&#39; );

$i = 1.2;
Mytest::round($i);
is( $i, 1.0, &#39;Rounding 1.2 to 1.0&#39; );</code></pre>

<p>Running &quot;<code>make test</code>&quot; should now print out that all nine tests are okay.</p>

<p>Notice that in these new test cases, the argument passed to round was a scalar variable. You might be wondering if you can round a constant or literal. To see what happens, temporarily add the following line to Mytest.t:</p>

<pre><code>Mytest::round(3);</code></pre>

<p>Run &quot;<code>make test</code>&quot; and notice that Perl dies with a fatal error. Perl won&#39;t let you change the value of constants!</p>

<h2 id="What&#39;s-new-here?"><a class="permalink" href="perlxstut.html#What&#39;s-new-here?">#</a><a id="What1"></a><a id="Whats-new-here"></a>What&#39;s new here?</h2>

<ul>

<li><p>We&#39;ve made some changes to Makefile.PL. In this case, we&#39;ve specified an extra library to be linked into the extension&#39;s shared library, the math library libm in this case. We&#39;ll talk later about how to write XSUBs that can call every routine in a library.</p>

</li>
<li><p>The value of the function is not being passed back as the function&#39;s return value, but by changing the value of the variable that was passed into the function. You might have guessed that when you saw that the return value of round is of type &quot;void&quot;.</p>

</li>
</ul>

<h2 id="Input-and-Output-Parameters"><a class="permalink" href="perlxstut.html#Input-and-Output-Parameters">#</a><a id="Input"></a>Input and Output Parameters</h2>

<p>You specify the parameters that will be passed into the XSUB on the line(s) after you declare the function&#39;s return value and name. Each input parameter line starts with optional whitespace, and may have an optional terminating semicolon.</p>

<p>The list of output parameters occurs at the very end of the function, just after the OUTPUT: directive. The use of RETVAL tells Perl that you wish to send this value back as the return value of the XSUB function. In Example 3, we wanted the &quot;return value&quot; placed in the original variable which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.</p>

<h2 id="The-XSUBPP-Program"><a class="permalink" href="perlxstut.html#The-XSUBPP-Program">#</a><a id="The"></a>The XSUBPP Program</h2>

<p>The <b>xsubpp</b> program takes the XS code in the .xs file and translates it into C code, placing it in a file whose suffix is .c. The C code created makes heavy use of the C functions within Perl.</p>

<h2 id="The-TYPEMAP-file"><a class="permalink" href="perlxstut.html#The-TYPEMAP-file">#</a><a id="The1"></a>The TYPEMAP file</h2>

<p>The <b>xsubpp</b> program uses rules to convert from Perl&#39;s data types (scalar, array, etc.) to C&#39;s data types (int, char, etc.). These rules are stored in the typemap file ($PERLLIB/ExtUtils/typemap). There&#39;s a brief discussion below, but all the nitty-gritty details can be found in <a href="perlxstypemap.html">perlxstypemap</a>. If you have a new-enough version of perl (5.16 and up) or an upgraded XS compiler (<code>ExtUtils::ParseXS</code> 3.13_01 or better), then you can inline typemaps in your XS instead of writing separate files. Either way, this typemap thing is split into three parts:</p>

<p>The first section maps various C data types to a name, which corresponds somewhat with the various Perl types. The second section contains C code which <b>xsubpp</b> uses to handle input parameters. The third section contains C code which <b>xsubpp</b> uses to handle output parameters.</p>

<p>Let&#39;s take a look at a portion of the .c file created for our extension. The file name is Mytest.c:</p>

<pre><code>XS(XS_Mytest_round)
{
    dXSARGS;
    if (items != 1)
	Perl_croak(aTHX_ &quot;Usage: Mytest::round(arg)&quot;);
    PERL_UNUSED_VAR(cv); /* -W */
    {
	double  arg = (double)SvNV(ST(0));	/* XXXXX */
	if (arg &gt; 0.0) {
		arg = floor(arg + 0.5);
	} else if (arg &lt; 0.0) {
		arg = ceil(arg - 0.5);
	} else {
		arg = 0.0;
	}
	sv_setnv(ST(0), (double)arg);	/* XXXXX */
	SvSETMAGIC(ST(0));
    }
    XSRETURN_EMPTY;
}</code></pre>

<p>Notice the two lines commented with &quot;XXXXX&quot;. If you check the first part of the typemap file (or section), you&#39;ll see that doubles are of type T_DOUBLE. In the INPUT part of the typemap, an argument that is T_DOUBLE is assigned to the variable arg by calling the routine SvNV on something, then casting it to double, then assigned to the variable arg. Similarly, in the OUTPUT section, once arg has its final value, it is passed to the sv_setnv function to be passed back to the calling subroutine. These two functions are explained in <a href="perlguts.html">perlguts</a>; we&#39;ll talk more later about what that &quot;ST(0)&quot; means in the section on the argument stack.</p>

<h2 id="Warning-about-Output-Arguments"><a class="permalink" href="perlxstut.html#Warning-about-Output-Arguments">#</a><a id="Warning"></a>Warning about Output Arguments</h2>

<p>In general, it&#39;s not a good idea to write extensions that modify their input parameters, as in Example 3. Instead, you should probably return multiple values in an array and let the caller handle them (we&#39;ll do this in a later example). However, in order to better accommodate calling pre-existing C routines, which often do modify their input parameters, this behavior is tolerated.</p>

<h2 id="EXAMPLE-4"><a class="permalink" href="perlxstut.html#EXAMPLE-4">#</a><a id="EXAMPLE3"></a>EXAMPLE 4</h2>

<p>In this example, we&#39;ll now begin to write XSUBs that will interact with pre-defined C libraries. To begin with, we will build a small library of our own, then let h2xs write our .pm and .xs files for us.</p>

<p>Create a new directory called Mytest2 at the same level as the directory Mytest. In the Mytest2 directory, create another directory called mylib, and cd into that directory.</p>

<p>Here we&#39;ll create some files that will generate a test library. These will include a C source file and a header file. We&#39;ll also create a Makefile.PL in this directory. Then we&#39;ll make sure that running make at the Mytest2 level will automatically run this Makefile.PL file and the resulting Makefile.</p>

<p>In the mylib directory, create a file mylib.h that looks like this:</p>

<pre><code>#define TESTVAL	4

extern double	foo(int, long, const char*);</code></pre>

<p>Also create a file mylib.c that looks like this:</p>

<pre><code>#include &lt;stdlib.h&gt;
#include &quot;mylib.h&quot;

double
foo(int a, long b, const char *c)
{
	return (a + b + atof(c) + TESTVAL);
}</code></pre>

<p>And finally create a file Makefile.PL that looks like this:</p>

<pre><code>use ExtUtils::MakeMaker;
$Verbose = 1;
WriteMakefile(
    NAME  =&gt; &#39;Mytest2::mylib&#39;,
    SKIP  =&gt; [qw(all static static_lib dynamic dynamic_lib)],
    clean =&gt; {&#39;FILES&#39; =&gt; &#39;libmylib$(LIB_EXT)&#39;},
);


sub MY::top_targets {
	&#39;
all :: static

pure_all :: static

static ::       libmylib$(LIB_EXT)

libmylib$(LIB_EXT): $(O_FILES)
	$(AR) cr libmylib$(LIB_EXT) $(O_FILES)
	$(RANLIB) libmylib$(LIB_EXT)

&#39;;
}</code></pre>

<p>Make sure you use a tab and not spaces on the lines beginning with &quot;$(AR)&quot; and &quot;$(RANLIB)&quot;. Make will not function properly if you use spaces. It has also been reported that the &quot;cr&quot; argument to $(AR) is unnecessary on Win32 systems.</p>

<p>We will now create the main top-level Mytest2 files. Change to the directory above Mytest2 and run the following command:</p>

<pre><code class="plaintext">% h2xs -O -n Mytest2 Mytest2/mylib/mylib.h</code></pre>

<p>This will print out a warning about overwriting Mytest2, but that&#39;s okay. Our files are stored in Mytest2/mylib, and will be untouched.</p>

<p>The normal Makefile.PL that h2xs generates doesn&#39;t know about the mylib directory. We need to tell it that there is a subdirectory and that we will be generating a library in it. Let&#39;s add the argument MYEXTLIB to the WriteMakefile call so that it looks like this:</p>

<pre><code>WriteMakefile(
    NAME         =&gt; &#39;Mytest2&#39;,
    VERSION_FROM =&gt; &#39;Mytest2.pm&#39;, # finds $VERSION
    LIBS         =&gt; [&#39;&#39;],   # e.g., &#39;-lm&#39;
    DEFINE       =&gt; &#39;&#39;,     # e.g., &#39;-DHAVE_SOMETHING&#39;
    INC          =&gt; &#39;&#39;,     # e.g., &#39;-I/usr/include/other&#39;
    MYEXTLIB     =&gt; &#39;mylib/libmylib$(LIB_EXT)&#39;,
);</code></pre>

<p>and then at the end add a subroutine (which will override the pre-existing subroutine). Remember to use a tab character to indent the line beginning with &quot;cd&quot;!</p>

<pre><code>sub MY::postamble {
&#39;
$(MYEXTLIB): mylib/Makefile
	cd mylib &amp;&amp; $(MAKE) $(PASSTHRU)
&#39;;
}</code></pre>

<p>Let&#39;s also fix the MANIFEST file by appending the following three lines:</p>

<pre><code class="plaintext">mylib/Makefile.PL
mylib/mylib.c
mylib/mylib.h</code></pre>

<p>To keep our namespace nice and unpolluted, edit the .pm file and change the variable <code>@EXPORT</code> to <code>@EXPORT_OK</code>. Finally, in the .xs file, edit the #include line to read:</p>

<pre><code class="plaintext">#include &quot;mylib/mylib.h&quot;</code></pre>

<p>And also add the following function definition to the end of the .xs file:</p>

<pre><code class="plaintext">double
foo(a,b,c)
	int             a
	long            b
	const char *    c
    OUTPUT:
	RETVAL</code></pre>

<p>Now we also need to create a typemap because the default Perl doesn&#39;t currently support the <code>const char *</code> type. Include a new TYPEMAP section in your XS code before the above function:</p>

<pre><code class="plaintext">        TYPEMAP: &lt;&lt;END
	const char *	T_PV
        END</code></pre>

<p>Now run perl on the top-level Makefile.PL. Notice that it also created a Makefile in the mylib directory. Run make and watch that it does cd into the mylib directory and run make in there as well.</p>

<p>Now edit the Mytest2.t script and change the number of tests to &quot;5&quot;, and add the following lines to the end of the script:</p>

<pre><code>is( Mytest2::foo( 1, 2, &quot;Hello, world!&quot; ), 7 );
is( Mytest2::foo( 1, 2, &quot;0.0&quot; ),           7 );
ok( abs( Mytest2::foo( 0, 0, &quot;-3.4&quot; ) - 0.6 ) &lt;= 0.01 );</code></pre>

<p>(When dealing with floating-point comparisons, it is best to not check for equality, but rather that the difference between the expected and actual result is below a certain amount (called epsilon) which is 0.01 in this case)</p>

<p>Run &quot;<code>make test</code>&quot; and all should be well. There are some warnings on missing tests for the Mytest2::mylib extension, but you can ignore them.</p>

<h2 id="What-has-happened-here?"><a class="permalink" href="perlxstut.html#What-has-happened-here?">#</a><a id="What2"></a><a id="What-has-happened-here"></a>What has happened here?</h2>

<p>Unlike previous examples, we&#39;ve now run h2xs on a real include file. This has caused some extra goodies to appear in both the .pm and .xs files.</p>

<ul>

<li><p>In the .xs file, there&#39;s now a #include directive with the absolute path to the mylib.h header file. We changed this to a relative path so that we could move the extension directory if we wanted to.</p>

</li>
<li><p>There&#39;s now some new C code that&#39;s been added to the .xs file. The purpose of the <code>constant</code> routine is to make the values that are #define&#39;d in the header file accessible by the Perl script (by calling either <code>TESTVAL</code> or <code>&amp;Mytest2::TESTVAL</code>). There&#39;s also some XS code to allow calls to the <code>constant</code> routine.</p>

</li>
<li><p>The .pm file originally exported the name <code>TESTVAL</code> in the <code>@EXPORT</code> array. This could lead to name clashes. A good rule of thumb is that if the #define is only going to be used by the C routines themselves, and not by the user, they should be removed from the <code>@EXPORT</code> array. Alternately, if you don&#39;t mind using the &quot;fully qualified name&quot; of a variable, you could move most or all of the items from the <code>@EXPORT</code> array into the <code>@EXPORT_OK</code> array.</p>

</li>
<li><p>If our include file had contained #include directives, these would not have been processed by h2xs. There is no good solution to this right now.</p>

</li>
<li><p>We&#39;ve also told Perl about the library that we built in the mylib subdirectory. That required only the addition of the <code>MYEXTLIB</code> variable to the WriteMakefile call and the replacement of the postamble subroutine to cd into the subdirectory and run make. The Makefile.PL for the library is a bit more complicated, but not excessively so. Again we replaced the postamble subroutine to insert our own code. This code simply specified that the library to be created here was a static archive library (as opposed to a dynamically loadable library) and provided the commands to build it.</p>

</li>
</ul>

<h2 id="Anatomy-of-.xs-file"><a class="permalink" href="perlxstut.html#Anatomy-of-.xs-file">#</a><a id="Anatomy"></a>Anatomy of .xs file</h2>

<p>The .xs file of <a href="perlxstut.html#EXAMPLE-4">&quot;EXAMPLE 4&quot;</a> contained some new elements. To understand the meaning of these elements, pay attention to the line which reads</p>

<pre><code class="plaintext">MODULE = Mytest2		PACKAGE = Mytest2</code></pre>

<p>Anything before this line is plain C code which describes which headers to include, and defines some convenience functions. No translations are performed on this part, apart from having embedded POD documentation skipped over (see <a href="perlpod.html">perlpod</a>) it goes into the generated output C file as is.</p>

<p>Anything after this line is the description of XSUB functions. These descriptions are translated by <b>xsubpp</b> into C code which implements these functions using Perl calling conventions, and which makes these functions visible from Perl interpreter.</p>

<p>Pay a special attention to the function <code>constant</code>. This name appears twice in the generated .xs file: once in the first part, as a static C function, then another time in the second part, when an XSUB interface to this static C function is defined.</p>

<p>This is quite typical for .xs files: usually the .xs file provides an interface to an existing C function. Then this C function is defined somewhere (either in an external library, or in the first part of .xs file), and a Perl interface to this function (i.e. &quot;Perl glue&quot;) is described in the second part of .xs file. The situation in <a href="perlxstut.html#EXAMPLE-1">&quot;EXAMPLE 1&quot;</a>, <a href="perlxstut.html#EXAMPLE-2">&quot;EXAMPLE 2&quot;</a>, and <a href="perlxstut.html#EXAMPLE-3">&quot;EXAMPLE 3&quot;</a>, when all the work is done inside the &quot;Perl glue&quot;, is somewhat of an exception rather than the rule.</p>

<h2 id="Getting-the-fat-out-of-XSUBs"><a class="permalink" href="perlxstut.html#Getting-the-fat-out-of-XSUBs">#</a><a id="Getting"></a>Getting the fat out of XSUBs</h2>

<p>In <a href="perlxstut.html#EXAMPLE-4">&quot;EXAMPLE 4&quot;</a> the second part of .xs file contained the following description of an XSUB:</p>

<pre><code class="plaintext">double
foo(a,b,c)
	int             a
	long            b
	const char *    c
    OUTPUT:
	RETVAL</code></pre>

<p>Note that in contrast with <a href="perlxstut.html#EXAMPLE-1">&quot;EXAMPLE 1&quot;</a>, <a href="perlxstut.html#EXAMPLE-2">&quot;EXAMPLE 2&quot;</a> and <a href="perlxstut.html#EXAMPLE-3">&quot;EXAMPLE 3&quot;</a>, this description does not contain the actual <i>code</i> for what is done during a call to Perl function foo(). To understand what is going on here, one can add a CODE section to this XSUB:</p>

<pre><code>double
foo(a,b,c)
	int             a
	long            b
	const char *    c
    CODE:
	RETVAL = foo(a,b,c);
    OUTPUT:
	RETVAL</code></pre>

<p>However, these two XSUBs provide almost identical generated C code: <b>xsubpp</b> compiler is smart enough to figure out the <code>CODE:</code> section from the first two lines of the description of XSUB. What about <code>OUTPUT:</code> section? In fact, that is absolutely the same! The <code>OUTPUT:</code> section can be removed as well, <i>as far as <code>CODE:</code> section or <code>PPCODE:</code> section</i> is not specified: <b>xsubpp</b> can see that it needs to generate a function call section, and will autogenerate the OUTPUT section too. Thus one can shortcut the XSUB to become:</p>

<pre><code class="plaintext">double
foo(a,b,c)
	int             a
	long            b
	const char *    c</code></pre>

<p>Can we do the same with an XSUB</p>

<pre><code>int
is_even(input)
	int	input
    CODE:
	RETVAL = (input % 2 == 0);
    OUTPUT:
	RETVAL</code></pre>

<p>of <a href="perlxstut.html#EXAMPLE-2">&quot;EXAMPLE 2&quot;</a>? To do this, one needs to define a C function <code>int is_even(int input)</code>. As we saw in <a href="perlxstut.html#Anatomy-of-.xs-file">&quot;Anatomy of .xs file&quot;</a>, a proper place for this definition is in the first part of .xs file. In fact a C function</p>

<pre><code>int
is_even(int arg)
{
	return (arg % 2 == 0);
}</code></pre>

<p>is probably overkill for this. Something as simple as a <code>#define</code> will do too:</p>

<pre><code class="plaintext">#define is_even(arg)	((arg) % 2 == 0)</code></pre>

<p>After having this in the first part of .xs file, the &quot;Perl glue&quot; part becomes as simple as</p>

<pre><code class="plaintext">int
is_even(input)
	int	input</code></pre>

<p>This technique of separation of the glue part from the workhorse part has obvious tradeoffs: if you want to change a Perl interface, you need to change two places in your code. However, it removes a lot of clutter, and makes the workhorse part independent from idiosyncrasies of Perl calling convention. (In fact, there is nothing Perl-specific in the above description, a different version of <b>xsubpp</b> might have translated this to TCL glue or Python glue as well.)</p>

<h2 id="More-about-XSUB-arguments"><a class="permalink" href="perlxstut.html#More-about-XSUB-arguments">#</a><a id="More"></a>More about XSUB arguments</h2>

<p>With the completion of Example 4, we now have an easy way to simulate some real-life libraries whose interfaces may not be the cleanest in the world. We shall now continue with a discussion of the arguments passed to the <b>xsubpp</b> compiler.</p>

<p>When you specify arguments to routines in the .xs file, you are really passing three pieces of information for each argument listed. The first piece is the order of that argument relative to the others (first, second, etc). The second is the type of argument, and consists of the type declaration of the argument (e.g., int, char*, etc). The third piece is the calling convention for the argument in the call to the library function.</p>

<p>While Perl passes arguments to functions by reference, C passes arguments by value; to implement a C function which modifies data of one of the &quot;arguments&quot;, the actual argument of this C function would be a pointer to the data. Thus two C functions with declarations</p>

<pre><code>int string_length(char *s);
int upper_case_char(char *cp);</code></pre>

<p>may have completely different semantics: the first one may inspect an array of chars pointed by s, and the second one may immediately dereference <code>cp</code> and manipulate <code>*cp</code> only (using the return value as, say, a success indicator). From Perl one would use these functions in a completely different manner.</p>

<p>One conveys this info to <b>xsubpp</b> by replacing <code>*</code> before the argument by <code>&amp;</code>. <code>&amp;</code> means that the argument should be passed to a library function by its address. The above two function may be XSUB-ified as</p>

<pre><code class="plaintext">int
string_length(s)
	char *	s

int
upper_case_char(cp)
	char	&amp;cp</code></pre>

<p>For example, consider:</p>

<pre><code class="plaintext">int
foo(a,b)
	char	&amp;a
	char *	b</code></pre>

<p>The first Perl argument to this function would be treated as a char and assigned to the variable a, and its address would be passed into the function foo. The second Perl argument would be treated as a string pointer and assigned to the variable b. The <i>value</i> of b would be passed into the function foo. The actual call to the function foo that <b>xsubpp</b> generates would look like this:</p>

<pre><code>foo(&amp;a, b);</code></pre>

<p><b>xsubpp</b> will parse the following function argument lists identically:</p>

<pre><code class="plaintext">char	&amp;a
char&amp;a
char	&amp; a</code></pre>

<p>However, to help ease understanding, it is suggested that you place a &quot;&amp;&quot; next to the variable name and away from the variable type), and place a &quot;*&quot; near the variable type, but away from the variable name (as in the call to foo above). By doing so, it is easy to understand exactly what will be passed to the C function; it will be whatever is in the &quot;last column&quot;.</p>

<p>You should take great pains to try to pass the function the type of variable it wants, when possible. It will save you a lot of trouble in the long run.</p>

<h2 id="The-Argument-Stack"><a class="permalink" href="perlxstut.html#The-Argument-Stack">#</a><a id="The2"></a>The Argument Stack</h2>

<p>If we look at any of the C code generated by any of the examples except example 1, you will notice a number of references to ST(n), where n is usually 0. &quot;ST&quot; is actually a macro that points to the n&#39;th argument on the argument stack. ST(0) is thus the first argument on the stack and therefore the first argument passed to the XSUB, ST(1) is the second argument, and so on.</p>

<p>When you list the arguments to the XSUB in the .xs file, that tells <b>xsubpp</b> which argument corresponds to which of the argument stack (i.e., the first one listed is the first argument, and so on). You invite disaster if you do not list them in the same order as the function expects them.</p>

<p>The actual values on the argument stack are pointers to the values passed in. When an argument is listed as being an OUTPUT value, its corresponding value on the stack (i.e., ST(0) if it was the first argument) is changed. You can verify this by looking at the C code generated for Example 3. The code for the round() XSUB routine contains lines that look like this:</p>

<pre><code>double  arg = (double)SvNV(ST(0));
/* Round the contents of the variable arg */
sv_setnv(ST(0), (double)arg);</code></pre>

<p>The arg variable is initially set by taking the value from ST(0), then is stored back into ST(0) at the end of the routine.</p>

<p>XSUBs are also allowed to return lists, not just scalars. This must be done by manipulating stack values ST(0), ST(1), etc, in a subtly different way. See <a href="perlxs.html">perlxs</a> for details.</p>

<p>XSUBs are also allowed to avoid automatic conversion of Perl function arguments to C function arguments. See <a href="perlxs.html">perlxs</a> for details. Some people prefer manual conversion by inspecting <code>ST(i)</code> even in the cases when automatic conversion will do, arguing that this makes the logic of an XSUB call clearer. Compare with <a href="perlxstut.html#Getting-the-fat-out-of-XSUBs">&quot;Getting the fat out of XSUBs&quot;</a> for a similar tradeoff of a complete separation of &quot;Perl glue&quot; and &quot;workhorse&quot; parts of an XSUB.</p>

<p>While experts may argue about these idioms, a novice to Perl guts may prefer a way which is as little Perl-guts-specific as possible, meaning automatic conversion and automatic call generation, as in <a href="perlxstut.html#Getting-the-fat-out-of-XSUBs">&quot;Getting the fat out of XSUBs&quot;</a>. This approach has the additional benefit of protecting the XSUB writer from future changes to the Perl API.</p>

<h2 id="Extending-your-Extension"><a class="permalink" href="perlxstut.html#Extending-your-Extension">#</a><a id="Extending"></a>Extending your Extension</h2>

<p>Sometimes you might want to provide some extra methods or subroutines to assist in making the interface between Perl and your extension simpler or easier to understand. These routines should live in the .pm file. Whether they are automatically loaded when the extension itself is loaded or only loaded when called depends on where in the .pm file the subroutine definition is placed. You can also consult <a href="AutoLoader.html">AutoLoader</a> for an alternate way to store and load your extra subroutines.</p>

<h2 id="Documenting-your-Extension"><a class="permalink" href="perlxstut.html#Documenting-your-Extension">#</a><a id="Documenting"></a>Documenting your Extension</h2>

<p>There is absolutely no excuse for not documenting your extension. Documentation belongs in the .pm file. This file will be fed to pod2man, and the embedded documentation will be converted to the manpage format, then placed in the blib directory. It will be copied to Perl&#39;s manpage directory when the extension is installed.</p>

<p>You may intersperse documentation and Perl code within the .pm file. In fact, if you want to use method autoloading, you must do this, as the comment inside the .pm file explains.</p>

<p>See <a href="perlpod.html">perlpod</a> for more information about the pod format.</p>

<h2 id="Installing-your-Extension"><a class="permalink" href="perlxstut.html#Installing-your-Extension">#</a><a id="Installing"></a>Installing your Extension</h2>

<p>Once your extension is complete and passes all its tests, installing it is quite simple: you simply run &quot;make install&quot;. You will either need to have write permission into the directories where Perl is installed, or ask your system administrator to run the make for you.</p>

<p>Alternately, you can specify the exact directory to place the extension&#39;s files by placing a &quot;PREFIX=/destination/directory&quot; after the make install (or in between the make and install if you have a brain-dead version of make). This can be very useful if you are building an extension that will eventually be distributed to multiple systems. You can then just archive the files in the destination directory and distribute them to your destination systems.</p>

<h2 id="EXAMPLE-5"><a class="permalink" href="perlxstut.html#EXAMPLE-5">#</a><a id="EXAMPLE4"></a>EXAMPLE 5</h2>

<p>In this example, we&#39;ll do some more work with the argument stack. The previous examples have all returned only a single value. We&#39;ll now create an extension that returns an array.</p>

<p>This extension is very Unix-oriented (struct statfs and the statfs system call). If you are not running on a Unix system, you can substitute for statfs any other function that returns multiple values, you can hard-code values to be returned to the caller (although this will be a bit harder to test the error case), or you can simply not do this example. If you change the XSUB, be sure to fix the test cases to match the changes.</p>

<p>Return to the Mytest directory and add the following code to the end of Mytest.xs:</p>

<pre><code>void
statfs(path)
	char *  path
    INIT:
	int i;
	struct statfs buf;

    PPCODE:
	i = statfs(path, &amp;buf);
	if (i == 0) {
		XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
		XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
		XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
		XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
		XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
		XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
		XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
	} else {
		XPUSHs(sv_2mortal(newSVnv(errno)));
	}</code></pre>

<p>You&#39;ll also need to add the following code to the top of the .xs file, just after the include of &quot;XSUB.h&quot;:</p>

<pre><code class="plaintext">#include &lt;sys/vfs.h&gt;</code></pre>

<p>Also add the following code segment to Mytest.t while incrementing the &quot;9&quot; tests to &quot;11&quot;:</p>

<pre><code>    my @a;

	@a = Mytest::statfs(&quot;/blech&quot;);
	ok( scalar(@a) == 1 &amp;&amp; $a[0] == 2 );

	@a = Mytest::statfs(&quot;/&quot;);
	is( scalar(@a), 7 );</code></pre>

<h2 id="New-Things-in-this-Example"><a class="permalink" href="perlxstut.html#New-Things-in-this-Example">#</a><a id="New"></a>New Things in this Example</h2>

<p>This example added quite a few new concepts. We&#39;ll take them one at a time.</p>

<ul>

<li><p>The INIT: directive contains code that will be placed immediately after the argument stack is decoded. C does not allow variable declarations at arbitrary locations inside a function, so this is usually the best way to declare local variables needed by the XSUB. (Alternatively, one could put the whole <code>PPCODE:</code> section into braces, and put these declarations on top.)</p>

</li>
<li><p>This routine also returns a different number of arguments depending on the success or failure of the call to statfs. If there is an error, the error number is returned as a single-element array. If the call is successful, then a 7-element array is returned. Since only one argument is passed into this function, we need room on the stack to hold the 7 values which may be returned.</p>

<p>We do this by using the PPCODE: directive, rather than the CODE: directive. This tells <b>xsubpp</b> that we will be managing the return values that will be put on the argument stack by ourselves.</p>

</li>
<li><p>When we want to place values to be returned to the caller onto the stack, we use the series of macros that begin with &quot;XPUSH&quot;. There are five different versions, for placing integers, unsigned integers, doubles, strings, and Perl scalars on the stack. In our example, we placed a Perl scalar onto the stack. (In fact this is the only macro which can be used to return multiple values.)</p>

<p>The XPUSH* macros will automatically extend the return stack to prevent it from being overrun. You push values onto the stack in the order you want them seen by the calling program.</p>

</li>
<li><p>The values pushed onto the return stack of the XSUB are actually mortal SV&#39;s. They are made mortal so that once the values are copied by the calling program, the SV&#39;s that held the returned values can be deallocated. If they were not mortal, then they would continue to exist after the XSUB routine returned, but would not be accessible. This is a memory leak.</p>

</li>
<li><p>If we were interested in performance, not in code compactness, in the success branch we would not use <code>XPUSHs</code> macros, but <code>PUSHs</code> macros, and would pre-extend the stack before pushing the return values:</p>

<pre><code>EXTEND(SP, 7);</code></pre>

<p>The tradeoff is that one needs to calculate the number of return values in advance (though overextending the stack will not typically hurt anything but memory consumption).</p>

<p>Similarly, in the failure branch we could use <code>PUSHs</code> <i>without</i> extending the stack: the Perl function reference comes to an XSUB on the stack, thus the stack is <i>always</i> large enough to take one return value.</p>

</li>
</ul>

<h2 id="EXAMPLE-6"><a class="permalink" href="perlxstut.html#EXAMPLE-6">#</a><a id="EXAMPLE5"></a>EXAMPLE 6</h2>

<p>In this example, we will accept a reference to an array as an input parameter, and return a reference to an array of hashes. This will demonstrate manipulation of complex Perl data types from an XSUB.</p>

<p>This extension is somewhat contrived. It is based on the code in the previous example. It calls the statfs function multiple times, accepting a reference to an array of filenames as input, and returning a reference to an array of hashes containing the data for each of the filesystems.</p>

<p>Return to the Mytest directory and add the following code to the end of Mytest.xs:</p>

<pre><code>    SV *
    multi_statfs(paths)
	    SV * paths
	INIT:
	    AV * results;
	    SSize_t numpaths = 0, n;
	    int i;
	    struct statfs buf;

	    SvGETMAGIC(paths);
	    if ((!SvROK(paths))
		|| (SvTYPE(SvRV(paths)) != SVt_PVAV)
		|| ((numpaths = av_top_index((AV *)SvRV(paths))) &lt; 0))
	    {
		XSRETURN_UNDEF;
	    }
	    results = (AV *)sv_2mortal((SV *)newAV());
	CODE:
	    for (n = 0; n &lt;= numpaths; n++) {
		HV * rh;
		STRLEN l;
		SV * path = *av_fetch((AV *)SvRV(paths), n, 0);
		char * fn = SvPVbyte(path, l);

		i = statfs(fn, &amp;buf);
		if (i != 0) {
		    av_push(results, newSVnv(errno));
		    continue;
		}

		rh = (HV *)sv_2mortal((SV *)newHV());

		hv_store(rh, &quot;f_bavail&quot;, 8, newSVnv(buf.f_bavail), 0);
		hv_store(rh, &quot;f_bfree&quot;,  7, newSVnv(buf.f_bfree),  0);
		hv_store(rh, &quot;f_blocks&quot;, 8, newSVnv(buf.f_blocks), 0);
		hv_store(rh, &quot;f_bsize&quot;,  7, newSVnv(buf.f_bsize),  0);
		hv_store(rh, &quot;f_ffree&quot;,  7, newSVnv(buf.f_ffree),  0);
		hv_store(rh, &quot;f_files&quot;,  7, newSVnv(buf.f_files),  0);
		hv_store(rh, &quot;f_type&quot;,   6, newSVnv(buf.f_type),   0);

		av_push(results, newRV_inc((SV *)rh));
	    }
	    RETVAL = newRV_inc((SV *)results);
	OUTPUT:
	    RETVAL</code></pre>

<p>And add the following code to Mytest.t, while incrementing the &quot;11&quot; tests to &quot;13&quot;:</p>

<pre><code>my $results = Mytest::multi_statfs([ &#39;/&#39;, &#39;/blech&#39; ]);
ok( ref $results-&gt;[0] );
ok( ! ref $results-&gt;[1] );</code></pre>

<h2 id="New-Things-in-this-Example1"><a class="permalink" href="perlxstut.html#New-Things-in-this-Example1">#</a><a id="New1"></a>New Things in this Example</h2>

<p>There are a number of new concepts introduced here, described below:</p>

<ul>

<li><p>This function does not use a typemap. Instead, we declare it as accepting one SV* (scalar) parameter, and returning an SV* value, and we take care of populating these scalars within the code. Because we are only returning one value, we don&#39;t need a <code>PPCODE:</code> directive - instead, we use <code>CODE:</code> and <code>OUTPUT:</code> directives.</p>

</li>
<li><p>When dealing with references, it is important to handle them with caution. The <code>INIT:</code> block first calls SvGETMAGIC(paths), in case paths is a tied variable. Then it checks that <code>SvROK</code> returns true, which indicates that paths is a valid reference. (Simply checking <code>SvROK</code> won&#39;t trigger FETCH on a tied variable.) It then verifies that the object referenced by paths is an array, using <code>SvRV</code> to dereference paths, and <code>SvTYPE</code> to discover its type. As an added test, it checks that the array referenced by paths is non-empty, using the <code>av_top_index</code> function (which returns -1 if the array is empty). The XSRETURN_UNDEF macro is used to abort the XSUB and return the undefined value whenever all three of these conditions are not met.</p>

</li>
<li><p>We manipulate several arrays in this XSUB. Note that an array is represented internally by an AV* pointer. The functions and macros for manipulating arrays are similar to the functions in Perl: <code>av_top_index</code> returns the highest index in an AV*, much like $#array; <code>av_fetch</code> fetches a single scalar value from an array, given its index; <code>av_push</code> pushes a scalar value onto the end of the array, automatically extending the array as necessary.</p>

<p>Specifically, we read pathnames one at a time from the input array, and store the results in an output array (results) in the same order. If statfs fails, the element pushed onto the return array is the value of errno after the failure. If statfs succeeds, though, the value pushed onto the return array is a reference to a hash containing some of the information in the statfs structure.</p>

<p>As with the return stack, it would be possible (and a small performance win) to pre-extend the return array before pushing data into it, since we know how many elements we will return:</p>

<pre><code>av_extend(results, numpaths);</code></pre>

</li>
<li><p>We are performing only one hash operation in this function, which is storing a new scalar under a key using <code>hv_store</code>. A hash is represented by an HV* pointer. Like arrays, the functions for manipulating hashes from an XSUB mirror the functionality available from Perl. See <a href="perlguts.html">perlguts</a> and <a href="perlapi.html">perlapi</a> for details.</p>

</li>
<li><p>To create a reference, we use the <code>newRV_inc</code> function. Note that you can cast an AV* or an HV* to type SV* in this case (and many others). This allows you to take references to arrays, hashes and scalars with the same function. Conversely, the <code>SvRV</code> function always returns an SV*, which may need to be cast to the appropriate type if it is something other than a scalar (check with <code>SvTYPE</code>).</p>

</li>
<li><p>At this point, xsubpp is doing very little work - the differences between Mytest.xs and Mytest.c are minimal.</p>

</li>
</ul>

<h2 id="EXAMPLE-7-(Coming-Soon)"><a class="permalink" href="perlxstut.html#EXAMPLE-7-(Coming-Soon)">#</a><a id="EXAMPLE6"></a><a id="EXAMPLE-7-Coming-Soon"></a>EXAMPLE 7 (Coming Soon)</h2>

<p>XPUSH args AND set RETVAL AND assign return value to array</p>

<h2 id="EXAMPLE-8-(Coming-Soon)"><a class="permalink" href="perlxstut.html#EXAMPLE-8-(Coming-Soon)">#</a><a id="EXAMPLE7"></a><a id="EXAMPLE-8-Coming-Soon"></a>EXAMPLE 8 (Coming Soon)</h2>

<p>Setting $!</p>

<h2 id="EXAMPLE-9-Passing-open-files-to-XSes"><a class="permalink" href="perlxstut.html#EXAMPLE-9-Passing-open-files-to-XSes">#</a><a id="EXAMPLE8"></a>EXAMPLE 9 Passing open files to XSes</h2>

<p>You would think passing files to an XS is difficult, with all the typeglobs and stuff. Well, it isn&#39;t.</p>

<p>Suppose that for some strange reason we need a wrapper around the standard C library function <code>fputs()</code>. This is all we need:</p>

<pre><code class="plaintext">#define PERLIO_NOT_STDIO 0  /* For co-existence with stdio only */
#define PERL_NO_GET_CONTEXT /* This is more efficient */
#include &quot;EXTERN.h&quot;
#include &quot;perl.h&quot;
#include &quot;XSUB.h&quot;

#include &lt;stdio.h&gt;

int
fputs(s, stream)
  char *          s
  FILE *          stream</code></pre>

<p>The real work is done in the standard typemap.</p>

<p>For more details, see <a href="perlapio.html#Co-existence-with-stdio">&quot;Co-existence with stdio&quot; in perlapio</a>.</p>

<p><b>But</b> you lose all the fine stuff done by the perlio layers. This calls the stdio function <code>fputs()</code>, which knows nothing about them.</p>

<p>The standard typemap offers three variants of PerlIO *: <code>InputStream</code> (T_IN), <code>InOutStream</code> (T_INOUT) and <code>OutputStream</code> (T_OUT). A bare <code>PerlIO *</code> is considered a T_INOUT. If it matters in your code (see below for why it might) #define or typedef one of the specific names and use that as the argument or result type in your XS file.</p>

<p>The standard typemap does not contain PerlIO * before perl 5.7, but it has the three stream variants. Using a PerlIO * directly is not backwards compatible unless you provide your own typemap.</p>

<p>For streams coming <i>from</i> perl the main difference is that <code>OutputStream</code> will get the output PerlIO * - which may make a difference on a socket. Like in our example...</p>

<p>For streams being handed <i>to</i> perl a new file handle is created (i.e. a reference to a new glob) and associated with the PerlIO * provided. If the read/write state of the PerlIO * is not correct then you may get errors or warnings from when the file handle is used. So if you opened the PerlIO * as &quot;w&quot; it should really be an <code>OutputStream</code> if open as &quot;r&quot; it should be an <code>InputStream</code>.</p>

<p>Now, suppose you want to use perlio layers in your XS. We&#39;ll use the perlio <code>PerlIO_puts()</code> function as an example.</p>

<p>In the C part of the XS file (above the first MODULE line) you have</p>

<pre><code>	#define OutputStream	PerlIO *
    or
	typedef PerlIO *	OutputStream;</code></pre>

<p>And this is the XS code:</p>

<pre><code>int
perlioputs(s, stream)
	char *          s
	OutputStream	stream
CODE:
	RETVAL = PerlIO_puts(stream, s);
OUTPUT:
	RETVAL</code></pre>

<p>We have to use a <code>CODE</code> section because <code>PerlIO_puts()</code> has the arguments reversed compared to <code>fputs()</code>, and we want to keep the arguments the same.</p>

<p>Wanting to explore this thoroughly, we want to use the stdio <code>fputs()</code> on a PerlIO *. This means we have to ask the perlio system for a stdio <code>FILE *</code>:</p>

<pre><code>int
perliofputs(s, stream)
	char *          s
	OutputStream	stream
PREINIT:
	FILE *fp = PerlIO_findFILE(stream);
CODE:
	if (fp != (FILE*) 0) {
		RETVAL = fputs(s, fp);
	} else {
		RETVAL = -1;
	}
OUTPUT:
	RETVAL</code></pre>

<p>Note: <code>PerlIO_findFILE()</code> will search the layers for a stdio layer. If it can&#39;t find one, it will call <code>PerlIO_exportFILE()</code> to generate a new stdio <code>FILE</code>. Please only call <code>PerlIO_exportFILE()</code> if you want a <i>new</i> <code>FILE</code>. It will generate one on each call and push a new stdio layer. So don&#39;t call it repeatedly on the same file. <code>PerlIO_findFILE()</code> will retrieve the stdio layer once it has been generated by <code>PerlIO_exportFILE()</code>.</p>

<p>This applies to the perlio system only. For versions before 5.7, <code>PerlIO_exportFILE()</code> is equivalent to <code>PerlIO_findFILE()</code>.</p>

<h2 id="Troubleshooting-these-Examples"><a class="permalink" href="perlxstut.html#Troubleshooting-these-Examples">#</a><a id="Troubleshooting"></a>Troubleshooting these Examples</h2>

<p>As mentioned at the top of this document, if you are having problems with these example extensions, you might see if any of these help you.</p>

<ul>

<li><p>In versions of 5.002 prior to the gamma version, the test script in Example 1 will not function properly. You need to change the &quot;use lib&quot; line to read:</p>

<pre><code>use lib &#39;./blib&#39;;</code></pre>

</li>
<li><p>In versions of 5.002 prior to version 5.002b1h, the test.pl file was not automatically created by h2xs. This means that you cannot say &quot;make test&quot; to run the test script. You will need to add the following line before the &quot;use extension&quot; statement:</p>

<pre><code>use lib &#39;./blib&#39;;</code></pre>

</li>
<li><p>In versions 5.000 and 5.001, instead of using the above line, you will need to use the following line:</p>

<pre><code>BEGIN { unshift(@INC, &quot;./blib&quot;) }</code></pre>

</li>
<li><p>This document assumes that the executable named &quot;perl&quot; is Perl version 5. Some systems may have installed Perl version 5 as &quot;perl5&quot;.</p>

</li>
</ul>

<h1 id="See-also"><a class="permalink" href="perlxstut.html#See-also">#</a><a id="See"></a>See also</h1>

<p>For more information, consult <a href="perlguts.html">perlguts</a>, <a href="perlapi.html">perlapi</a>, <a href="perlxs.html">perlxs</a>, <a href="perlmod.html">perlmod</a>, <a href="perlapio.html">perlapio</a>, and <a href="perlpod.html">perlpod</a></p>

<h1 id="Author"><a class="permalink" href="perlxstut.html#Author">#</a>Author</h1>

<p>Jeff Okamoto &lt;<i>okamoto@corp.hp.com</i>&gt;</p>

<p>Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce.</p>

<p>PerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons.</p>

<p>Changes for h2xs as of Perl 5.8.x by Renee Baecker</p>

<p>This document is now maintained as part of Perl itself.</p>

<h2 id="Last-Changed"><a class="permalink" href="perlxstut.html#Last-Changed">#</a><a id="Last"></a>Last Changed</h2>

<p>2020-10-05</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
